package com.example.bdmanagerapplication

import android.content.Context
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


object  MyUtils {
    //软键盘回车键输入事件
//该方法需至于 handlerText 之前否则初始化时会执行handlertetxt里的内容
    fun EditText.setOnKeySearchListener(search: () -> Unit) {
        this.isSingleLine=true
        imeOptions= EditorInfo.IME_ACTION_SEARCH
        setOnKeyListener { v, keyCode, event ->
            if(KeyEvent.ACTION_DOWN == event.action){
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    search()
                    hideKeyboard()
                }
                false
            }else{
                false
            }
        }
    }
    fun View.hideKeyboard() {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(windowToken, 0)

    }
    /***ViewModel携程 处理错误*/
    fun BaseViewModel.launch(block: suspend () -> Unit) = viewModelScope.launch {
        try {
            withContext(Dispatchers.IO) {
                block()
            }
        } catch (e: Exception) {
            // Handle exception
        }
    }

}